import { defineStore } from 'pinia'
import { marked } from 'marked'

let msgCount = 0
let index = 0
let totalMsg = ''
let interval = null  // 保存interval ID

export const userMsgStore = defineStore('userMsgStore', {
  // 持久化
  persist: true,
  state: () => {
    return {
      list: [],
      isPaused: false,  // 控制暂停的状态
    }
  },
  actions: {
    userAddMsg(msg) {
      this.list.push({
        role: 'user',
        content: marked(msg),
        status: 2,
      })
      totalMsg = ""
    },
    aiAddMsg(content, status) {
      if (this.isPaused) return; // 如果已暂停，直接返回
      
      if (status === 0) {
        totalMsg = content
      } else {
        totalMsg += content
      }
      msgCount = totalMsg.length

      let runMsg = this.list.find((i) => i.status !== 2)
      if (!runMsg) {
        this.list.push({
          role: 'assistant',
          content: '',
          status: status,
        })
        index = 0
      } else {
        if (interval) clearInterval(interval); // 清除现有的 interval

        interval = setInterval(() => {
          if (this.isPaused) {
            clearInterval(interval) // 如果暂停，停止消息显示
          } else if (index < msgCount) {
            runMsg.content += totalMsg[index]
            index++
          } else {
            clearInterval(interval)  // 停止消息显示
            if (status === 2) {
              runMsg.status = 2
              //alert('回答完成')
            }
          }
        }, 30)
      }
    },
    copyToClipboard(content) {
      navigator.clipboard.writeText(content).then(() => {
        //alert('复制成功！')
      }).catch(err => {
        //alert('复制失败：' + err)
      })
    },
    pauseDisplay() {
      this.isPaused = true
      clearInterval(interval)
      let runMsg = this.list.find((i) => i.status !== 2)
      if (runMsg) {
        runMsg.status = 2  // 将未完成的消息状态设置为完成
        runMsg.content += ' (已中断)'  // 添加中断标志
        alert('已暂停')
      }
      totalMsg = ''  // 清空内容
      index = 0
    },
    resetDisplay() {
      this.isPaused = false
      totalMsg = ''
      index = 0
      clearInterval(interval)
    }
  }
})
